import {
  Component,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  OnInit,
  Input,
  TemplateRef,
  Output,
  EventEmitter,
  OnDestroy,
} from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { ArrayService, copy } from '@delon/util';
import { UploadFile, NzMessageService } from 'ng-zorro-antd';
import { handleImg } from '@shared';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { ProductImageComponent } from '../product-image.component';
import { Subscription } from 'rxjs';

/**
 * 图片文件管理
 */
@Component({
  selector: 'app-pic-manger',
  templateUrl: './file-manager.component.html',
  styleUrls: ['./file-manager.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FileManagerComponent implements OnInit, OnDestroy {
  constructor(
    public http: _HttpClient,
    private cdr: ChangeDetectorRef,
    private arrSrv: ArrayService,
    private msg: NzMessageService,
    private sanitizer: DomSanitizer,
    private settings: SettingsService,
    public parent: ProductImageComponent,
  ) {
    this.ref$ = this.parent.$sign.subscribe(res => {
      if (res === 'reload') {
        this.load(this.s.current);
      }
    });
  }

  private ref$: Subscription;
  showType: 'big' | 'small' = 'big';
  s: any = { size: 24, current: 1, q: '' };
  loading = false;
  list: any[] = [];
  item: any;
  path: number[] = [0];
  total = 0;
  moveModel = false;
  moveId = '';
  folderNodes: any[] = [];
  renameModel = false;
  renameTitle = '';
  _p = '';
  _type: string;
  @Input()
  set type(v) {
    this._type = v;
    this.load(1);
  }

  @Input()
  params: any;

  @Input()
  actions: TemplateRef<any>;

  @Input()
  multiple: boolean | number = false;

  @Output()
  selected = new EventEmitter<any>();

  @Input()
  set p(val) {
    this._p = val;
    if (!this.loading) {
      this.load(1);
    }
  }
  auth_btn_edit = false;
  auth_btn_del = false;

  ngOnInit() {
    this.auth_btn_del = this.settings.user.permissions.sys_prod_del_pic;
    this.auth_btn_edit = this.settings.user.permissions.sys_prod_modify_pic;
  }

  ngOnDestroy() {
    this.ref$.unsubscribe();
  }

  /**
   * 分页获取数据
   * @param current 页码
   */
  load(current: number) {
    const data = {
      ...this.s,
      current,
      ...this.params,
    };
    if (this._p) {
      data.keyword = this._p;
    }
    this.loading = true;
    this.http.get(`/cf/prod/sys-prod/imgpage/${this._type}`, data).subscribe((res: any) => {
      this.loading = false;
      res.data.records.forEach(p => {
        p.pic = './assets/img/noimg.png';
        if (!p.noimg) {
          handleImg(this.http, this.sanitizer, p.url, (url: SafeUrl) => {
            p.pic = url;
            this.cdr.detectChanges();
          });
        }
        // if (!p.noimg) {
        //   p.pic = `/cf/admin/sysfile/f/${p.url}`;
        // } else {
        //   p.pic = p.url;
        // }
      });
      this.list = res.data.records;

      this.total = res.data.total;
      this.cdr.detectChanges();
    });
  }

  getCode(mp: string, type: 'link' | 'code') {
    return type === 'link'
      ? `${window.location.origin + window.location.pathname}/cf/admin/sysfile/f/${mp}`
      : `<img src="${window.location.origin + window.location.pathname}/cf/admin/sysfile/f/${mp}">`;
  }

  /**
   * 选中文件
   * @param i 对象
   */
  cho(i: any) {
    i.selected = !i.selected;
    this.selected.emit(i);
    this.cdr.detectChanges();
  }

  rename(i: any) {
    this.renameModel = true;
    this.item = i;
    this.renameTitle = i.title;
  }
  renameOk() {
    this.http
      .post(`/file/rename`, {
        id: this.item.id,
        title: this.renameTitle,
      })
      .subscribe(() => {
        this.msg.success('Success');
        this.item.title = this.renameTitle;
        this.renameModel = false;
        this.cdr.detectChanges();
      });
  }

  remove(productCd: string, idx: number) {
    this.http.delete(`/cf/prod/sys-prod/delpic/${productCd}`).subscribe(() => {
      this.msg.success('操作成功');
      this.load(this.s.current);
    });
  }

  copyData(mp: string, type: 'link' | 'code') {
    copy(this.getCode(mp, type)).then(() => this.msg.success('复制成功'));
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的文件类型: ${file.type}`);
    }
    const isLt4M = file.size / 1024 / 1024 < 4;
    if (!isLt4M) {
      this.msg.warning('物料图片不能超过4Mb');
    }
    return (isJPG || isPNG) && isLt4M;
  };

  handleChange(i, ie: UploadFile) {
    if (ie.type === 'success') {
      this.http.put(`/cf/prod/sys-prod/modifypic/${i.productCd}`, ie.file.response.data.fileName).subscribe(res => {
        if (res.status === 200) {
          this.msg.success('上传成功');
          this.load(this.s.current);
        }
      });
    }
  }

  private getBase64(img: File, callback: (img: any) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
}
